<template>
  <el-card class="attr-card">
    <el-form @submit.prevent>
      <el-form-item label="属性名">
        <el-input
          placeholder="请输入属性名"
          class="attr-input"
          v-model="attrFormData.attrName"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrFormData.attrName"
          @click="showAddAttrValue"
          >添加属性值</el-button
        >

        <el-table :data="attrFormData.attrValueList" border class="attr-table">
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          ></el-table-column>
          <!-- index : 当前元素的下标 -->
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                size="small"
                v-if="row.isEdit"
                ref="input"
                v-model="row.valueName"
                @blur="goShow(row, $index)"
                @keyup.enter="goShow(row, $index)"
              />
              <div v-else @click="goEdit(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-tooltip content="删除属性值" placement="top" effect="light">
                <div class="attr-wrap">
                  <el-popconfirm
                    :title="`您确认要删除 ${row.valueName} 属性值吗？`"
                    @confirm="delAttrValue($index)"
                  >
                    <template #reference>
                      <el-button type="danger" :icon="Delete" size="small" />
                    </template>
                  </el-popconfirm>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :disabled="isBtnDisabled" @click="submitForm"
          >确定</el-button
        >
        <el-button @click="emit('setIsShowAttrList', true)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script lang="ts">
export default {
  name: 'SaveOrUpdateAttr',
}
</script>

<script lang="ts" setup>
import { Plus, Delete } from '@element-plus/icons-vue'
import { reactive, ref, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useCategoryStore } from '@/stores/category'
import { saveUpdateAttrApi } from '@/api/product/attr'
import type {
  SaveAttrItem,
  SaveAttrValueItem,
} from '@/api/product/model/attrModel'

// 获取el-input元素
const input = ref()

const emit = defineEmits(['setIsShowAttrList'])

//声明接受属性
const props = defineProps<{
  attr: SaveAttrItem
}>()

// 表单数据
const attrFormData = reactive<SaveAttrItem>(props.attr)

// 点击添加属性值按钮触发的函数
const showAddAttrValue = async () => {
  // 往数组添加一个{}，table就会显示一行数据
  attrFormData.attrValueList.push({
    valueName: '', //属性值名称
    isEdit: true, // 每一行数据的标识，代表是否显示编辑模式
  })
  await nextTick()
  // 让显示这行数据中input聚焦
  input.value.focus()
}
// 失去焦点切换到显示模式
const goShow = (row: SaveAttrValueItem, index: number) => {
  if (!row.valueName) {
    // 没值，删除当前行数据
    attrFormData.attrValueList.splice(index, 1)
    return
  }
  // 有值，切换到显示模式
  row.isEdit = false
}
// 点击切换到编辑模式
const goEdit = async (row: SaveAttrValueItem) => {
  // 变成编辑模式
  row.isEdit = true
  await nextTick()
  // 更新完在显示聚焦
  input.value.focus()
}

// 删除属性值
const delAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1)
}

// 按钮禁用
const isBtnDisabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.find((attrValue) => attrValue.valueName)
  )
})

const categoryStore = useCategoryStore()

// 提交表单
const submitForm = async () => {
  // 更新有id，发送就是更新的请求
  // 添加没有id，发送就是添加的请求
  await saveUpdateAttrApi({
    ...attrFormData,
    categoryId: categoryStore.category3Id as number, // 三级分类id
    categoryLevel: 3, // 三级分类
  })
  ElMessage.success(`${attrFormData.id ? '更新' : '添加'}属性成功`)
  emit('setIsShowAttrList', true)
}
</script>

<style scoped>
.attr-card {
  margin-top: 20px;
}
.attr-input {
  width: 200px;
}
.attr-table {
  margin-top: 10px;
}
.attr-wrap {
  display: inline-block;
}
</style>
